package leetcode_day._2022._202208._2131;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 946. 验证栈序列
 * 算法：栈 + 模拟
 *
 * @author yzh
 * @version 1.0
 * @date 2022/8/31 21:56
 */
public class _31 {

    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int n = pushed.length, p = 0;
        Deque<Integer> stack = new ArrayDeque<>();
        for (int push : pushed) {
            stack.push(push);
            while (!stack.isEmpty() && stack.peek() == popped[p]) {
                ++p;
                stack.pop();
            }
        }
        return p == n;
    }

    public boolean validateStackSequences_tow(int[] pushed, int[] popped) {
        int n = pushed.length, idx = 0;
        for (int i = 0, j = 0; i < n; i++) {
            pushed[idx++] = pushed[i];
            while (idx > 0 && pushed[idx - 1] == popped[j]) {
                ++j;
                --idx;
            }
        }
        return idx == 0;
    }

}
